package com.gitee.wsl.logger.format

import com.gitee.wsl.logger.LogFormatter
import com.gitee.wsl.logger.LogLevel
import com.gitee.wsl.logger.LogPrinter
import com.gitee.wsl.logger.format


class AnsiEscapeFormat:LogFormatter {
    override fun format(
        level: LogLevel,
        tag: String,
        messageAny: Any?,
        throwable: Throwable?,
    ): String {
        return buildString {
            append("${level.ansiColorStart}[${level.name}]${level.ansiColorEnd} ")

            if (tag != null) {
                append("$tag: ")
            }

            append(messageAny?.toString())
        }
    }

    companion object{
        val instance = AnsiEscapeFormat()
    }

}


private const val ansiControlCode = '\u001B'
private const val ansiRed = "[31m"
private const val ansiGreen = "[32m"
private const val ansiYellow = "[33m"
private const val ansiBlue = "[34m"
private const val ansiMagenta = "[35m"
private const val ansiCyan = "[36m"
private const val ansiReset = "[0m"

internal val LogLevel.ansiColorStart: String
    get() {
        return when (this) {
            LogLevel.VERBOSE -> "$ansiControlCode$ansiGreen"
            LogLevel.DEBUG -> "$ansiControlCode$ansiBlue"
            LogLevel.INFO -> "$ansiControlCode$ansiCyan"
            LogLevel.WARNING -> "$ansiControlCode$ansiYellow"
            LogLevel.ERROR -> "$ansiControlCode$ansiRed"
            LogLevel.WTF -> "$ansiControlCode$ansiMagenta"
        }
    }

internal val LogLevel.ansiColorEnd: String
    get() {
        return when (this) {
            else -> "$ansiControlCode$ansiReset"
        }
    }


fun LogPrinter.useAnsiEscapeFormat(){
    format(AnsiEscapeFormat.instance)
}